/**
 * Created by DELL on 2018/9/14.
 */
;(function () {
  window.onload = function () {
    app.init();
    // 微信长按出现复制按钮
    document.oncontextmenu = function (e) {
      e.preventDefault();
    };
    document.addEventListener('click', function (e) {
      e.preventDefault();
    });

    document.body.addEventListener('touchmove', function (e) {
      // e.preventDefault();
    })
  };
  var app = window.app = {
    songsList: [],  // 歌曲列表
    userInfo: {}, // 用户信息
    hotList: [],  // 热门
    current_index: 0, // 当前选中歌曲
    playing_index: 0, // 当前游戏歌曲的index
    is_playingMusic: false,  // 是否正在播放自己的作品 状态
    swiper: null,
    swiper_index: 0,        // weiper 当前序号
    has_save: false,        // 是否已经保存
    wxconfig: new WxConfig(),
    init: function () {
      this.initScenes();
      this.playWorkManage = new PlayWork();
      // this.playGame_click();
    },
    initScenes: function () {
      this.loginScenes = new app.Login();
    },
    // swiper
    initSwiper: function () {
      var _this = this;
      this.swiper = new Swiper('.swiper-container', {
        spaceBetween: 30,
        pagination: {
          el: '.swiper-pagination',
        },
        on: {
          slideChange: function () {
            if (this.activeIndex === 2) {
              // 最后一页
              $('.swiper_next').text('我知道了');
            } else {
              $('.swiper_next').text('下一步');
            }
            _this.swiper_index = this.activeIndex;
          },
        },
      });
    },
    // 用户授权完成后的回调
    login_success_back: function (userInfo) {
      this.userInfo = userInfo || {};
      console.log(this.userInfo.login_source, 'this.userInfo.login_source');
      this.configWXsdk({});
      if (this.userInfo.is_legitimate || _isDevelopment) { // 合法登陆才获取
        this.getUserData();
        this.getSongs();
        this.getHotSongs();
      }
      this.initEvent();
    },

    initEvent: function () {
      var _this = this;
      $('.btn_join').click(function () {
        _this.initSongsScenes();
        _this.showSongList();
      });
      // 开始游戏
      $('.btn_startGame').click(function () {
        _this.playGame_click()
      });
      // 再次挑战
      $('.btn_replay').click(function () {
        _this.playEnd_own();
        _this.playWorkManage.stop_play();
        _this.showSongList();
      });
      // 切换歌曲
      $('.page2 .cd_center').click(this.nextSong.bind(this));
      // 热门列表点赞
      $('.hot_list_box').on('click', '.hot_zan', function () {
        var zan_index = $(this).parent().index();
        _this.zanAction(zan_index)
      });

      // 热门列表播放
      $('.hot_list_box').on('click', '.hot_play', function () {
        var zan_index = $(this).parent().index();
        if ($(this).hasClass('playing')) {  // 正在播放中  需要暂停
          $(this).removeClass('playing');
          // 暂停播放
          _this.playWorkManage.stop_play();
        } else {
          _this.playAction(zan_index);
          $('.hot_list_box .hot_play').removeClass('playing');
          $(this).addClass('playing');
        }
      });
      // 分享 -> 提交保存用户数据
      $('.btn_share').on('click', function () {
        _this.saveUserPlay(true)
      });

      // 分享页播放
      $('.btn_play_music').click(function () {
        _this.playMusic_click();
      });
      $('.page4 .cd_handle').click(function () {
        _this.playMusic_click();
      });
      // 分享浮层
      $('.page5').click(function () {
        $(this).fadeOut();
      });
      // swiper 下一步
      $('.swiper_next').click(function () {
        _this.swiper_click();
      });

      // 打开央视新闻
      $('#openApp').click(function () {
        _this.openAppNotInWx();
      })
    },
    initSongsScenes: function () {
      var userInfo = app.loginScenes.getUserInfo();
      console.log(userInfo);
      var default_head = 'images/default_head.png';

      var head_img = userInfo.avatar || default_head;

      $('.user_box .user_avatar').css({
        'background-image': 'url(' + head_img + ')'
      });
      $('.user_nickname').text(userInfo.nickname);
    },
    // 获取用户演奏信息
    getUserData: function () {
      $.ajax({
        url: _api.getUserPlayNum,
        type: 'POST',
        dataType: 'json',
        data: {
          user_code: this.userInfo.uid
        }
      }).done(function (resp, textStatus, xhr) {
        var data = resp.data;
        if (resp.code === 0) {
          $('.songs_num').text(data.play_num);
        } else {
          alert(resp.msg);
        }
      }).fail(function (xhr, err, textStatus) {
        console.log('内部服务器错误');
      })
    },
    // 获取歌曲列表
    getSongs: function () {
      var _this = this;
      $.ajax({
        url: _api.getPlayList,
        type: 'POST',
        dataType: 'json',
        data: {
          user_code: this.userInfo.uid
        }
      }).done(function (resp) {
        if (resp.code === 0) {
          _this.songsList = resp.data || [];
          _this.checkoutSong(0);


          // _this.showGameEnd()
        } else {
          alert(resp.msg);
        }
      }).fail(function (xhr, err, textStatus) {
        console.log('内部服务器错误');
      })
    },
    // 获取热门歌曲
    getHotSongs: function () {
      var _this = this;
      $.ajax({
        url: _api.getHotList,
        type: 'POST',
        dataType: 'json',
        data: {}
      }).done(function (resp) {
        if (resp.code === 0) {
          _this.hotList = resp.data || [];
          _this.renderHotList();
        } else {
          alert(resp.msg);
        }
      }).fail(function (xhr, err, textStatus) {
        console.log('内部服务器错误');
      })
    },

    // 渲染热门列表
    renderHotList: function () {
      var hotList = this.hotList;
      var hotArr = [];
      for (var i = 0; i < hotList.length; i++) {
        var hotItem = hotList[i];
        var nickname = hotItem.nickname || '默认昵称';
        var headImg = hotItem.cover || 'images/default_head.png';
        var zan_num = tools.numToString(hotItem.zan_num);
        hotArr.push('' +
          '<div class="hot_item"> ' +
          '<div class="hot_image"><img src=' + headImg + ' alt=""></div>' +

          '<div class="hot_play"> ' +
          '<div class="hot_play_icon"></div> ' +
          '<div class="hot_play_text">播放</div> ' +
          '</div>' +

          '<div class="hot_zan"> ' +
          '<div class="zan_icon"></div> ' +
          '<div class="zan_animate_box"></div> ' +
          '<div class="zan_num" data-num=' + hotItem.zan_num + '>' + zan_num + '</div> ' +
          '</div>' +

          ' <div class="hot_info"> ' +
          '<div class="music_name">' + hotItem.title + '</div> ' +
          '<div class="music_player">by: ' + nickname + '</div> </div> </div>')
      }
      $('.hot_list').html(hotArr.join(''))
    },
    // 切换当前选中歌曲
    checkoutSong: function (index) {
      var songsList = this.songsList;
      var current_index = index || 0;
      this.current_index = current_index;
      var currentSong = songsList[current_index];
      $('.music_info .music_name').text(currentSong.title);
      var diff = currentSong.diff;
      var gide_class = 'gide_' + diff;
      $('.gide_star').removeClass('gide_1 gide_2 gide_3').addClass(gide_class);
      $('.cd_box .cd_cover').css({
        'background-image': 'url(' + currentSong.cover + ')'
      })
    },
    // 下一曲
    nextSong: function () {
      var _this = this;
      var current_index = this.current_index;
      var total = this.songsList.length;
      var next_index = 0;
      if (total > 0 && current_index < total - 1) {
        next_index = current_index + 1;
      }
      $('.page2 .disc_box').removeClass('playing_disc');
      $('.page2 .cd_handle').velocity({
          rotateZ: "-15deg"
        }, 300, function () {
          $('.page2 .cd_box_inner').velocity(
            {
              top: ["-10rem", "linear"],
              left: ['-10rem', 'ease-in']
            }, {
              complete: function () {
                checkNextSong();
              },
              duration: 500
            }
          );
        }
      );

      function checkNextSong() {
        $('.page2 .cd_box_inner').css({
          top: '10rem',
          left: '-10rem'
        });
        _this.checkoutSong(next_index);
        $('.page2 .cd_box_inner').velocity(
          {
            top: ["0rem", "linear"],
            left: ["0rem", "ease-out"]
          }, 500, function () {
            // handel还原
            $('.page2 .cd_handle').velocity({
                rotateZ: "0deg"
              }, 300, function () {
                $('.page2 .disc_box').addClass('playing_disc');
              }
            );

          })
      }

    },
    // 播放音频
    playAction: function (index) {
      var current_item = this.hotList[index];
      var playData = [];
      if (current_item.play_data) {
        playData = JSON.parse(current_item.play_data);
      }
      this.playWorkManage.stop_play();

      this.playWorkManage.init(current_item.music_id, playData, this.playEnd.bind(this));
      this.playWorkManage.start_play()


    },
    // 点赞
    zanAction: function (index) {
      var current_item = this.hotList[index];
      var zanNum_dom = $('.hot_list .hot_item').eq(index).find('.hot_zan .zan_num');
      var origin_num = zanNum_dom.attr('data-num') / 1;
      var new_num = origin_num + 1;
      var zan_num_format = tools.numToString(new_num);
      zanNum_dom.text(zan_num_format);
      zanNum_dom.attr('data-num', new_num);
      $.ajax({
        url: _api.zanPlay,
        type: 'POST',
        dataType: 'json',
        data: {
          uuid: current_item.uuid
        }
      }).done(function (resp) {
        if (resp.code === 0) {
        } else {
        }
      });
      var zan_animate_box = $('.hot_list .hot_item').eq(index).find('.zan_animate_box');
      this.zanAnimate(zan_animate_box);
    },
    // 点赞动画
    zanAnimate: function (zan_animate_box) {
      var _id = 'img_' + new Date().getTime();
      zan_animate_box.append('<img id="' + _id + '" class="zanfly" src="./images/2applaud@2x.png">');
      var _left_arr = ['-0.3rem', '-0.2rem', '0rem', '0.3rem', '0.5rem'];

      var _left = _left_arr[Math.round(Math.random() * _left_arr.length)];

      $('#' + _id).velocity(
        {
          bottom: "5.5rem",
          opacity: "0",
          // rotateZ: 360 * 2,
          scale: 1.5,
          left: _left
        }, {
          complete: function (elements) {
            $(elements).remove();
          },
          duration: 2000
        }
      );
    },
    // 歌曲列表
    showSongList: function () {
      $('.page1').fadeOut();
      $('.page4').fadeOut();
      $('.page2').show();
    },
    // 游戏页面
    showGamePage: function () {
      this.showGameLoading();
      this.playing_index = this.current_index;
      console.log(this.current_index, 'this.current_index')
      var canvas = document.querySelector('canvas');
      // 初始化曲谱
      var current_music_config = music_config[this.current_index];

      window.game.notation = current_music_config.music;  // 曲谱
      window.game.batTime = current_music_config.batTime;  // 一节时间

      // 初始化bg音乐
      // var bgAudio = Hilo.WebSound.getAudio({
      //   src: current_music_config.bg_music,
      //   loop: true,
      //   volume: 1
      // }).on('load', function (e) {
      // }).on('end', function (e) {
      // });

      console.log(current_music_config.bg_music);
      var bgAudio = new Audio(current_music_config.bg_music);
      bgAudio.load();

      window.game.bgAudio = bgAudio;

      var has_intro = localStorage.getItem('2018music_intro');
      if (has_intro !== '1') { // 未介绍过游戏 出现游戏介绍页
        $('.page_intro').fadeIn();
        this.initSwiper();
      }


      if (!canvas) {
        window.game.init();
      } else {
        window.game.gameReady();
      }

      $('.page2').fadeOut();
      $('.page3').show();
    },
    // 游戏加载
    showGameLoading: function () {
      // 暂时不需要加载游戏 直接进入
    },
    // 游戏结束页面
    showGameEnd: function () {
      // 计算分数
      var total = game.notation.length;
      var score = game.score;
      var percentage = score / total;

      console.log('用户正确率： ', percentage);
      if (percentage > 0.8) { // 你在本次弹奏中表现很棒哦~

        $('.music_dis span').html('你在本次弹奏中表现很棒哦~ 取得了 <b>' + score + '</b> 分');
      } else if (percentage > 0.5) { // 你在本次弹奏中表现一般~继续努力！
        $('.music_dis span').html('你在本次弹奏中表现一般~ 取得了 <b>' + score + '</b> 分，继续努力！');
      } else {               // 你在本次弹奏中表现的不是很好哦~加油！
        $('.music_dis span').html('你在本次弹奏中表现的不是很好哦~ 取得了 <b>'+ score + '</b> 分，加油!');
      }
      $('.page1').fadeOut();
      $('.page3').fadeOut();
      $('.page4').show();
      this.saveUserPlay();
    },
    // 点击播放乐曲
    playMusic_click: function () {
      var _this = this;
      if (!this.is_playingMusic) {
        this.is_playingMusic = true;
        $('.page4 .btn_play_music').fadeOut();
        $('.page4 .cd_handle').addClass('playing_handel');
        setTimeout(function () {
          $('.disc_box').addClass('playing_disc');
          _this.play_own_game();
        }, 300);
      }
    },
    // 预览自己的作品
    play_own_game: function () {
      var playingMusic = this.songsList[this.playing_index];
      var music_id = playingMusic.id;
      var playData = game.record;
      this.playWorkManage.stop_play();
      this.playWorkManage.init(music_id, playData, this.playEnd_own.bind(this));
      this.playWorkManage.start_play()
    },
    // 点击开始游戏
    playGame_click: function () {
      this.has_save = false; // 重置保存状态
      this.playWorkManage.stop_play();
      $('.hot_play').removeClass('playing');
      this.showGamePage();
    },
    // 显示loading
    show_loading: function (text) {
      var text = text || '加载中...';
      $('.loading .loading_content span').text(text);
      $('.loading').fadeIn();
    },
    //
    hide_loading: function () {
      $('.loading').fadeOut();
    },
    // 保存用户曲子
    saveUserPlay: function (show_tops) {
      if (this.has_save) { // 已经保存
        if (show_tops) {
          $('.page5').fadeIn();
          // APP中停止播放
          if (this.userInfo.login_source === 'app') {
            this.playEnd_own();
            this.playWorkManage.stop_play();
          }
        }
        return false;
      } else {            // 未保存 需要先提交项目在显示分享页
        this.show_loading('数据保存中...');
        var score = game.score;

        var _this = this;
        var playingMusic = this.songsList[this.playing_index];
        var music_id = playingMusic.id;
        var music_name = playingMusic.title;
        var play_data = JSON.stringify(game.record);
        var user_code = this.userInfo.uid;
        $.ajax({
          url: _api.submitUserPlay,
          type: 'POST',
          dataType: 'json',
          data: {
            music_id: music_id,
            play_data: play_data,
            user_code: user_code
          }
        }).done(function (resp) {
          if (resp.code === 0) {
            var user_play_num = resp.data.user_play_num || 0;

            $('.user_songs .songs_num').text(user_play_num);
            _this.has_save = true;
            var nickname = _this.userInfo.nickname || '';
            if (show_tops) {
              $('.page5').fadeIn();
            }
            // 保存结果的uuid
            var work_id = resp.data.uuid;
            // 重置分享链接
            _this.configWXsdk({
              link: _config.WXsharebaseLink + '?workid=' + work_id,
              title: nickname + '弹奏了一曲《' + music_name + '》,获得'+score+'分,邀你来弹~',
              desc: '',
              imgUrl: ''
            });
            setTimeout(_this.hide_loading, 1000);
          } else {
            alert('保存失败： ' + resp.msg);
            _this.hide_loading();
          }
        }).fail(function () {
          alert('保存失败： 内部服务器错误！');
          _this.hide_loading();
        })
      }
    },
    // 预览播放结束
    playEnd: function () {
      console.log('playEnd');
    },
    // 预览自己的作品结束
    playEnd_own: function () {
      $('.page4 .cd_handle').removeClass('playing_handel');
      $('.page4 .disc_box').removeClass('playing_disc');
      $('.page4 .btn_play_music').fadeIn();
      this.is_playingMusic = false;
    },
    //  swiper_click
    swiper_click: function () {
      if (this.swiper_index !== 2) { // 最后一页。开始游戏
        this.swiper.slideNext();
      } else {    // 开始游戏
        localStorage.setItem('2018music_intro', '1'); // 用户已经介绍过游戏玩法了
        $('.page_intro').fadeOut();
      }
    },
    // 呼起app
    openAppNotInWx: function () {
      var nativeUrl = {
        ios: 'com.foundaoCNNews://',
        android: 'com.cctv.ugc://'  // TODO: android scame 不能正常呼起首页
      };
      var downloadUrl = {
        ios: 'https://itunes.apple.com/cn/app/id1133052681?mt=8',
        android: 'https://www.newscctv.net/apkdownload/index.html'
      };
      // ios
      if (tools.is_iOS()) {
        var jump_url = nativeUrl.ios;
        location.href = jump_url; // 应跳到APP中相对应的详情页
        setTimeout(function () {
          location.href = downloadUrl.ios;
        }, 2000);
      } else {
        // Android
        var ifr = document.createElement('iframe');
        ifr.src = nativeUrl.android; // 应跳到APP中相对应的详情页
        ifr.style.display = 'none';
        var last = Date.now();
        document.body.appendChild(ifr);
        //程序切换到后台，计时器会被推迟
        setTimeout(function () {
          document.body.removeChild(ifr);
          if (Date.now() - last <= 1500) {
            //唤起失败，进入下载页
            location.href = downloadUrl.android;
          } else {
            //成功
          }
        }, 1000);
      }
    },
    // 配置微信
    configWXsdk: function (obj) {
      var nickname = this.userInfo.nickname || '';
      var wxconfig = this.wxconfig;
      var default_title = nickname + '邀请你弹奏一首《我爱你中国》';
      var appid = _config.appID;
      var link = obj.link || _config.appBaseLink;
      var title = obj.title || default_title;
      var desc = obj.desc || '弹得真好，忍不住单曲循环，余音不绝啊';
      var imgUrl = obj.imgUrl || _config.WXsharebaseIcon;
      wxconfig.init({
        appid: appid,
        url: window.location.href,
        link: link,
        debug: false,
        title: title,
        desc: desc,
        imgUrl: imgUrl
      });
    }
  }
})();